package com.irdstudio.apicenter.frame.web;

import java.util.Hashtable;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.irdstudio.apicenter.frame.core.dm.SWebAction;
import com.irdstudio.apicenter.frame.web.controller.AbstractController;

/**
 * Web交易总线主程序
 * 
 * @author guangming.li
 * @version 1.0
 * @date 2015-06-17
 */
public class MacmsControllerBus {

	/* WEB交易总线下支持的Web交易列表 */
	private Map<String, SWebAction> webActions = null;

	/* WEB交易总线下的控制器实例 */
	private Map<String, AbstractController> webControllers = null;

	/* 文本日志记录对象(Logback对象) */
	private final static Logger logger = LoggerFactory
			.getLogger(MacmsControllerBus.class);

	/* 总线配置信息是否已经检查通过 */
	private boolean ready;

	/**
	 * 构造函数
	 */
	public MacmsControllerBus() {
		this.ready = false;
		this.webActions = new Hashtable<String, SWebAction>();
		this.webControllers = new Hashtable<String, AbstractController>();
	}

	/**
	 * 通讯控制总线交易处理入口
	 * 
	 * @param tradeId
	 * @param request
	 * @param response
	 */
	public void execute(String tradeId, HttpServletRequest request,
			HttpServletResponse response) {

		// // 任何进入到通讯控制总线的交易请求必须记入数据库日志
		// long startMills = System.currentTimeMillis();
		// AppTradeLog calledLog = new AppTradeLog();
		// calledLog.setAppId(this.getAppBaseInfo().getAppId());
		// calledLog.setClientIp(ServletUtil.getRealClientIP(request));
		// calledLog.setClientUserid("admin");
		// calledLog.setStartTime(CurrentDateUtil.getTodayDateEx2());
		// calledLog.setTradeCode(tradeId);
		// calledLog.setTradeSerialNo(KeyUtil.createUniqueKey());
		//		
		// // 捕获所有交易处理过程中的异常情况并以JSON返回给应用端
		// try {
		//			
		// // 获取需要执行的交易的定义信息,如果没找到，直接返回JSON错误信息(超出处理范围)
		// MacmsTradeDefineVo tradeDefine = appTradeTable.get(tradeId);
		// if (tradeDefine == null) {
		// logger.error("Invalid request:" + tradeId);
		// throw new MacmsException("该交易无效，不在通讯总线处理范围之内");
		// }
		// StringBuffer sb = new StringBuffer("Accepted request,appId:");
		// sb.append(this.getAppBaseInfo().getAppId());
		// sb.append(",tradeId=").append(tradeId);
		// sb.append(",tradeName=").append(tradeDefine.getTradeName());
		// sb.append(",class=").append(tradeDefine.getTradeClass());
		// logger.info(sb.toString());
		// calledLog.setTradeName(tradeDefine.getTradeName());
		// calledLog.setForwardChannelId(tradeDefine.getForwardChannelId());
		//			
		// // 获得所有请求的参数集合
		// MaccsPacket inPacket = ServletUtil.getAllRequestValues(request);
		// logger.info("Accepted request,Parameter [" + inPacket.toString() +
		// "]");
		// calledLog.setInBuffer(inPacket.toString());
		//			
		// // 获得请求头(Cookie)
		// Cookie[] cookies = request.getCookies();
		// logger.info("Accepted request, header:" +
		// request.getHeader("Cookie"));
		// logger.info("Accepted request, Cookie:" + cookies);
		//			
		// // 实例 化交易处理控制类
		// IMaccsController tradeController = (IMaccsController) Class.forName(
		// tradeDefine.getTradeClass()).newInstance();
		//			
		// //记录交易
		// View view = tradeController.execute(tradeDefine, inPacket,
		// request,response);
		// calledLog.setOutBuffer(view.getViewData());
		//			
		// // 将Cookies写回到Response对象，返回给客户端
		// cookies = request.getCookies();
		// if (cookies != null) {
		// for (Cookie c : cookies) {
		// response.addCookie(c);
		// }
		// logger.info("Response cookies, values:" + cookies);
		// }
		//			
		// calledLog.setTradeResult(MaccsConstant.APP_TRADE_RESULT_SUCCESS);
		// view.renderView();
		//			
		// } catch (ClassNotFoundException e) {
		// e.printStackTrace();
		// calledLog.setTradeResult(MaccsConstant.APP_TRADE_RESULT_FAILURE);
		// MacmsRenderUtil.renderNormalErrorJsonView(
		// MacmsRenderUtil.TRADE_CLASS_NOT_FOUND, response);
		// } catch (InstantiationException e) {
		// e.printStackTrace();
		// calledLog.setTradeResult(MaccsConstant.APP_TRADE_RESULT_FAILURE);
		// MacmsRenderUtil.renderNormalErrorJsonView(
		// MacmsRenderUtil.TRADE_CLASS_NOT_FOUND, response);
		// } catch (IllegalAccessException e) {
		// e.printStackTrace();
		// calledLog.setTradeResult(MaccsConstant.APP_TRADE_RESULT_FAILURE);
		// MacmsRenderUtil.renderNormalErrorJsonView(
		// MacmsRenderUtil.TRADE_CLASS_EXCEPTION, response);
		// } catch (MacmsException e) {
		// e.printStackTrace();
		// calledLog.setTradeResult(MaccsConstant.APP_TRADE_RESULT_FAILURE);
		// MacmsRenderUtil.renderCustomErrorJsonView(e.getErrorCode(), e
		// .getMessage(), response);
		// } catch (Exception e) {
		// e.printStackTrace();
		// calledLog.setTradeResult(MaccsConstant.APP_TRADE_RESULT_FAILURE);
		// MacmsRenderUtil.renderCustomErrorJsonView(Integer
		// .toString(MacmsRenderUtil.CUSTOM_EXCEPTION),
		// "test" + e.getMessage(), response);
		// } finally{
		//			
		// // 登记交易结束时间并计算交易耗时（秒）
		// long endMills = System.currentTimeMillis();
		// calledLog.setEndTime(CurrentDateUtil.getTodayDateEx2());
		// calledLog.setCostTime(new BigDecimal(endMills - startMills)
		// .divide(new BigDecimal(1000.00)));
		//			
		// // 无论成功还是失败，写入日志进入数据库
		// MaccsLogExecutor.writeTradeCalledLog(calledLog);
		// }

	}

	/**
	 * 增加可处理的Web交易定义信息
	 * 
	 * @param tradeId
	 * @param mtdv
	 */
	public void addWebAction(String actionId, SWebAction webAction) {
		webActions.put(actionId, webAction);
	}

	/**
	 * 增加可用的Web控制器实例
	 * 
	 * @param actionType
	 *            不同类型的Web交易由不同的控制器执行
	 * @param controller
	 *            控制器实例
	 */
	public void addWebController(String actionType,
			AbstractController controller) {
		webControllers.put(actionType, controller);
	}

	public void setReady(boolean ready) {
		this.ready = ready;
	}

	public boolean isReady() {
		return ready;
	}

}
